
<template>
    <div id="improt">
        <span>请选择解压目录：</span>
        <el-select v-model="value" placeholder="请选择解压目录">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
        </el-select>
        <div style="margin:20px 0"></div>
        <span>请选择资源地址：</span>
        <div @click="startImport" style="display:inline-block">
            <el-input v-model="fileName" disabled placeholder="" style="width:400px;cursor: pointer;"></el-input>
        </div>
        <br>
        <el-button type="primary" @click="start">开始导入</el-button>
        <div v-if="isStart">
            <div style="margin-top:5vh">{{status}}</div>
            <el-progress :text-inside="true" :stroke-width="26" :percentage="percentage" :color="customColors" style="margin-top:1vh"></el-progress>
        </div>
        <!-- <el-button type="primary" @click="creatZip">生成zip</el-button> -->
        <!--<el-button type="primary" @click="clearDir('D:\\1599728700756')">清空文件夹</el-button>-->
    </div>
</template>

<script>
import { resolve } from 'url';
import { FileUtil } from '../../../../../../static/utils/FileUtil';
import { GeneratorFactory } from '../../../../../../static/lib/executor/GeneratorFactory';
import { GeneratorExecutor } from '../../../../../../static/lib/executor/GeneratorExecutor';
import { SqlLib } from '../../../../../../static/lib/sqlite/SqlLib';
import { UserResource } from '../../../../../../static/lib/sqlite/model/UserResource';
import { SqlLibUser } from '../../../../../../static/lib/sqlite/service/SqlLibUser';
import { Lesson } from '../../../../../../static/lib/sqlite/model/Lesson';
import { Downloaded } from '../../../../../../static/lib/sqlite/model/Downloaded';
import { GenBookZip } from '../../../../../../static/lib/import/GenBookZip';
const diskinfo = require('diskinfo');
const dialog = require('electron').remote.dialog
const unzip = require('node-unzip-2')
const fs = require('fs')
const path = require('path')
const _dirPatharry = []
export default {
    data() {
        return {
            fileName: '',
            options: [],
            value: '',
            isStart: false,
            step: 0,
            percentage: 0,
            status: '正在解压文件...',
            customColors: [
                { color: '#f56c6c', percentage: 20 },
                { color: '#e6a23c', percentage: 40 },
                { color: '#5cb87a', percentage: 60 },
                { color: '#1989fa', percentage: 80 },
                { color: '#6f7ad3', percentage: 100 }
            ]
        }
    },
    mounted() {
        diskinfo.getDrives((err, aDrives) => {
            let diskArry = []
            aDrives.forEach(v => {
                let str = v.mounted + path.sep
                if (diskArry.includes(str)) return
                diskArry.push(str)
                this.options.push({ value: str, label: v.mounted.substr(0, 1) + '盘' })
            })
        })
    },
    methods: {
        startImport() {
            if (!this.value) {
                this.$message.warning('请选择解压目录')
                return
            }
            dialog.showOpenDialog({
                title: '选择需要导入的文件',
                filters: [
                    {
                        name: 'ZIP',
                        extensions: ['zip']
                    }
                ],
                buttonLabel: "确定"
            }, file => {
                if (!file || file.length <= 0) return
                this.fileName = file[0]
            })
        },

        start() {
            this.status = '正在解压文件...'
            const dataNow = Date.now() + ''
            this.percentage = 0
            const resPath = window.$DATADIR + 'resc/'
            const entryPath = path.resolve(this.value, '/' + dataNow);
            console.log('正在解压文件...')
            this.isStart = true
            const entry = this.fileName
            const folder = unzip.Extract({ path: entryPath })
            const targetPath = path.resolve(window.$DATADIR, 'resc')
            let progress = 0;
            let readStream = fs.createReadStream(entry)
            readStream.pipe(folder);
            folder.on('error', err => {
                console.log(err)
            })
            readStream.on('end', () => {
                const unzipFileName = fs.readdirSync(entryPath)[0]
                this.status = '正在复制文件...'
                setTimeout(() => {
                    console.log('正在复制文件...')
                    let destPaths = [];

                    let pathMap = new Map()
                    FileUtil.staticsZipInfo(path.resolve(entryPath, unzipFileName), targetPath, true, destPaths, pathMap);
                    if (destPaths.length === 0) {
                        this.$message.error('复制文件失败或文件为空请重试')
                    }
                    this.step = 100 / pathMap.size
                    let copyNum = 0
                    let progressCallback = (resolve) => {
                        let percentage = parseFloat((this.percentage + this.step).toFixed(1))
                        if (percentage >= 100) {
                            this.percentage = 100
                        } else {
                            this.percentage = percentage
                        }
                        resolve();
                    }
                    let promiseArray = []
                    pathMap.forEach((item, key) => {
                        let copyFile = () => {
                            return new Promise(resolve => {
                                fs.copyFile(key, item, err => {
                                    if (err) {
                                        console.log('拷贝失败')
                                        console.log(err)
                                        progressCallback(resolve)
                                    }
                                    console.log(key + '拷贝完成')
                                    progressCallback(resolve)
                                    // if (copyNum >= pathMap.size) {
                                    //     setTimeout(() => {
                                    //         this.unzipResZip(zipNum, destPaths, entryPath, unzipFileName)
                                    //     }, 500);
                                    // }
                                })
                            })
                        }
                        promiseArray.push(copyFile)
                    })
                    let gen = GeneratorFactory.createGenerator(promiseArray)
                    let executor = new GeneratorExecutor();
                    executor.run(gen, () => {
                        setTimeout(() => {
                            this.percentage = 0
                            this.unzipResZip(destPaths, entryPath, unzipFileName)
                        }, 500);
                    })
                }, 2500);
            })

        },

        unzipResZip(destPaths, entryPath, unzipFileName) {
            let once = 1 //确保后续读取配置只执行一次
            this.step = Math.ceil(100 / destPaths.length)
            let progressCallback = (resolve) => {
                let percentage = this.percentage + this.step
                if (percentage >= 100) {
                    this.percentage = 100
                } else {
                    this.percentage = percentage
                }
                resolve();
            }
            this.status = '正在解压资源包...'
            console.log('正在解压资源包..')
            let promiseArray = [];
            destPaths.forEach(value => {
                let unzipFun = function () {
                    return new Promise(resolve => {
                        if (value.indexOf("PolyvVideo") !== -1) {//保利威视
                            FileUtil.unzipFileAndRename(value, false, false, function () {
                                progressCallback(resolve)
                            }, function () {
                                progressCallback(resolve)
                            });
                        } else {
                            FileUtil.unzipFileAndRename(value, true, true, function () {
                                progressCallback(resolve)
                            }, function () {
                                progressCallback(resolve)
                            });
                        }
                    })
                }
                promiseArray.push(unzipFun);
            });
            let gen = GeneratorFactory.createGenerator(promiseArray);
            let executor = new GeneratorExecutor();
            executor.run(gen, () => {
                if (once > 1) return
                once++
                console.log('读取描述文件')
                this.status = '正在读取配置文件'
                const description = fs.readFileSync(path.resolve(entryPath, unzipFileName, 'description.json'), 'utf-8')
                if (description) {
                    console.log('正在更新资源')
                    this.status = '正在更新资源'
                    let dataJson = JSON.parse(description)
                    this.updataDB(dataJson)
                }
                //删除解压文件
                console.log('开始清空文件夹')
                this.percentage = 0
                this.clearDir(entryPath)
                this.percentage = 100
                this.$message.success('导入成功,请等待10秒在进行其他操作')
                setTimeout(() => {
                    this.isStart = false
                }, 2000)
            });
        },
        //递归清空文件夹
        clearDir(dirPath) {
            let files = fs.readdirSync(dirPath)
            if (!Array.isArray(files)) {
                return
            }
            if (files.length === 0) {
                fs.rmdirSync(dirPath)
                return
            }
            files.forEach(file => {
                let newPath = path.resolve(dirPath, file)
                if (fs.statSync(newPath).isFile()) {
                    fs.unlinkSync(newPath);
                } else {
                    this.clearDir(newPath)
                }
            });
            fs.rmdirSync(dirPath)
            let per = this.percentage + 10
            per >= 100 ? this.percentage = 100 : this.percentage = 0
        },
        //更新数据库
        updataDB(dataJson) {
            let sqlLib = SqlLib.getInstance(window.$DBDIR)
            let user = SqlLibUser.queryCurrentUser(sqlLib)
            let keys = Object.keys(dataJson)
            let dataArry = []
            keys.forEach(key => {
                dataJson[key].forEach(item => {
                    let mapItem = null;
                    if (key === 'resources') {
                        mapItem = new UserResource()
                    } else if (key === 'lessons') {
                        mapItem = new Lesson()
                    } else {
                        mapItem = new Downloaded()
                    }
                    if (item.userId) {
                        item.userId = user.id
                    }
                    dataArry.push(Object.assign(mapItem, item))
                })
            })
            const step = 100 / dataArry.length
            dataArry.forEach(item => {
                sqlLib.updateOrInsertObjectById(item);
                (this.percentage += step) >= 100 || (this.percentage = 100)
            })
        },

        creatZip() {
            let genBook = new GenBookZip()
            genBook.generateBook()
        },

    }
}
</script>

<style lang="scss">
#improt {
    padding-top: 10vh;
    .el-input.is-disabled .el-input__inner{
        cursor: pointer;
    }
}
</style>
